package main;

import java.awt.event.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

import gui.LuaChooser;
import javax.swing.*;

import serial.SerialException;
import serial.SerialInterface;

@SuppressWarnings("serial")
public class ProgramBlaster extends gui.OutputFrame {
	private JMenuItem blaster;
	private LuaChooser chooser;
	private SerialInterface serial;

	private final static String PORT_PATH = ".portNames";
	
	public ProgramBlaster() {
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		JMenuBar bar = new JMenuBar();
		setJMenuBar(bar);
		
		JMenu fileMenu = new JMenu("File");
		bar.add(fileMenu);
		
		blaster = new JMenuItem("Blast file");
		blaster.addActionListener(new FileBlaster());
		fileMenu.add(blaster);
		
		chooser = new LuaChooser();
		
		serial = new SerialInterface(this);
		try {
			serial.loadPossibleNamesFrom(PORT_PATH);
			serial.setup(getClass().getName());
		} catch (FileNotFoundException e) {
			JOptionPane.showMessageDialog(null, "No port file; exiting...");
			System.exit(1);
		} catch (SerialException e) {
			JOptionPane.showMessageDialog(null, "Serial port problem");
			e.printStackTrace();
			System.exit(1);
		}
	}
	
	private class FileBlaster implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			int option = chooser.showOpenDialog(ProgramBlaster.this);
			if (option == JFileChooser.APPROVE_OPTION) {
				File choice = chooser.getSelectedFile();
				try {
					StringBuilder program = new StringBuilder();
					Scanner s = new Scanner(choice);
					while (s.hasNextLine()) {
						program.append(s.nextLine() + "\n");
					}
					
					serial.send(program.toString(), false);
					
				} catch (FileNotFoundException e1) {
					JOptionPane.showMessageDialog(null, "Problem opening " + choice.getName());
				} catch (SerialException e2) {
					JOptionPane.showMessageDialog(null, "Problem sending " + choice.getName() + " to robot");
					e2.printStackTrace();
				}
			}
		}
	}
	
	public static void main(String[] args) {
		new ProgramBlaster().setVisible(true);
	}
}
